package com.yeming.tinyid.application.controller;

import com.yeming.tinyid.service.TinyIdTokenService;
import com.yeming.tinyid.service.factory.impl.IdGeneratorFactoryServer;
import com.yeming.tinyid.util.enums.ResponseCodeEnum;
import com.yeming.tinyid.util.generator.IdGenerator;
import com.yeming.tinyid.util.response.ResponseResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author yeming.gao
 * @Description: tinyid生成控制层
 * @date 2020/7/29 10:02
 */
@RestController
public class IdGeneratorController {

    private static final Logger LOGGER = LoggerFactory.getLogger(IdGeneratorController.class);

    @Resource
    private TinyIdTokenService tinyIdTokenService;

    @Resource
    private IdGeneratorFactoryServer idGeneratorFactoryServer;

    @Value("${batch.size.max}")
    private Integer batchSizeMax;

    /**
     * 获取tinyId
     *
     * @param bizType 业务类型
     * @param token   token
     * @return ResponseResult<Long>
     */
    @GetMapping(path = "/nextId")
    public ResponseResult<Long> nextId(String bizType, String token) {
        LOGGER.info("获取bizType={}的tinyid", bizType);
        ResponseResult<Long> response = new ResponseResult<>();
        if (!tinyIdTokenService.canVisit(bizType, token)) {
            response.returnResp(ResponseCodeEnum.TOKEN_ERR);
            return response;
        }
        IdGenerator idGenerator = idGeneratorFactoryServer.getIdGenerator(bizType);
        response.returnSuccessWithData(idGenerator.nextId());
        return response;
    }

    /**
     * 批量获取tinyid
     *
     * @param bizType   业务类型
     * @param token     token
     * @param batchSize 批量获取个数
     * @return ResponseResult<List   <   Long>>
     */
    @GetMapping(path = "/nextBatchId")
    public ResponseResult<List<Long>> nextBatchId(String bizType, String token, Integer batchSize) {
        LOGGER.info("批量获取bizType={}的tinyid共{}个", bizType, batchSize);
        Integer newBatchSize = checkBatchSize(batchSize);
        ResponseResult<List<Long>> response = new ResponseResult<>();
        if (!tinyIdTokenService.canVisit(bizType, token)) {
            response.returnResp(ResponseCodeEnum.TOKEN_ERR);
            return response;
        }
        IdGenerator idGenerator = idGeneratorFactoryServer.getIdGenerator(bizType);
        response.returnSuccessWithData(idGenerator.nextId(newBatchSize));
        return response;
    }

    /**
     * batchSize最大限制
     *
     * @param batchSize 请参中的batchSize
     * @return Integer
     */
    private Integer checkBatchSize(Integer batchSize) {
        if (batchSize == null) {
            batchSize = 1;
        }
        if (batchSize > batchSizeMax) {
            batchSize = batchSizeMax;
        }
        return batchSize;
    }
}
